<template>
    <div>
        <div class="pay">
            <van-nav-bar style="z-index: 999;position: relative;" :placeholder=true fixed title="确认订单" left-arrow
                @click-left="$router.go(-1)" />
            <div class="orderList">
                <div class="orderItem">
                    <div class="orderLef">
                        <van-image width="85%" height="100%" fit="cover" radius="10"
                            :src="selectTicketInfo.info.activeImg" />
                    </div>
                    <div class="orderRig">
                        <div class="tit">{{ selectTicketInfo.info.name }}</div>
                        <div class="tickets">{{ selectTicketInfo.info.ticketType }}</div>
                        <div class="oRbottom">
                            <p class="oRLeft">
                                <span>{{ selectTicketInfo.info.description }}</span>
                                <span>￥{{ selectTicketInfo.info.price }}</span>
                            </p>
                            <span style="color:#fff">x{{ selectTicketInfo.num }}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="allMoney">
                <div class="monTop">
                    <p style="font-size: .28rem;">票品总价</p>
                    <p style="font-size: .32rem;">￥{{ allPrice }}</p>
                </div>
                <div class="monBtm">
                    温馨提示：该活动门票为电子券，一旦购买默认不支持退票退款，请悉知
                </div>
            </div>
            <div class="surePay">
                <div class="sureTop">
                    <div class="sureIcon" @click="isRead = !isRead">
                        <van-icon name="success" v-show="isRead" />
                    </div>
                    <p style="font-size: .28rem;">请勾选<span style="color: #fff;text-decoration: underline;"
                            @click="showAgreement">票品购买协议</span></p>
                </div>
                <div class="sureBtm">
                    <div class="sureBLeft">
                        <p style="font-size: .38rem;">￥{{ allPrice }}</p>
                        <p style="font-size: .26rem;color: #686980;">共{{ selectTicketInfo.num }}件，合计</p>
                    </div>
                    <van-button color="linear-gradient(to right, #575cfe, #5e80ff)" @click="goPay"
                        style="width: 70%;border-radius: .3rem;">确认并支付</van-button>
                </div>
            </div>
        </div>
    </div>
</template>
  
<script>
import { mapState } from 'vuex'
export default {
    name: 'PayIndex',
    data() {
        return {
            activeTicketInfo: {},
            isRead: true,
            orderId: '',
            ticketAgreement: '',
            code: '',
            openId: ''
        }
    },
    computed: {
        selectTicketInfo(){
            if(this.$store.state.collect.selectTicketInfo.info){
                return this.$store.state.collect.selectTicketInfo
            }else {
                return JSON.parse(localStorage.getItem('SelectTicketInfo'))
            }
        },
        allPrice() {
            return Number(this.selectTicketInfo.num) * Number(this.selectTicketInfo.info.price)
        }
    },
    methods: {
        toResult() {
            this.getWxPaySign()
            // if (this.isRead) {
            //     this.$router.push({
            //         path: '/payResult',
            //         query: {

            //         }
            //     })
            // }
        },
        callPaymentAPI(result) {
            return new Promise((resolve, reject) => {
                if (typeof WeixinJSBridge === 'undefined') {
                    if (document.addEventListener) {
                        document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady.bind(null, result, resolve, reject), false)
                    } else if (document.attachEvent) {
                        document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady.bind(null, result, resolve, reject))
                        document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady.bind(null, result, resolve, reject));
                    }
                } else {
                    this.onBridgeReady(result, resolve, reject)
                }
            })
        },
        onBridgeReady(result, resolve, reject) {
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                appId: result.appId,
                timeStamp: result.timeStamp,
                nonceStr: result.nonceStr,
                package: result.package,
                signType: result.signType,
                paySign: result.paySign
            },
                function (res) {
                    if (res.err_msg === "get_brand_wcpay_request:ok") {
                        resolve(res)
                    } else {
                        reject(res)
                    }
                }
            );
        },
        // 创建订单
        createOrder() {
            let creatOrder = {
                activityId: Number(this.selectTicketInfo.id),
                remark: '',
                ticketList: [{
                    ticketId: this.selectTicketInfo.info.id,
                    number: this.selectTicketInfo.info.number
                }]
            }
            this.$axios.post(`front/order`, creatOrder).then((res) => {
                if (res.code == 0) {
                    this.orderId = res.result
                    this.wxPay()
                } else {
                    console.log('创建订单失败');
                }
            });
        },
        goPay() {
            if (this.isRead == true) {
                if (this.$store.state.user.userinfo) {
                    this.sureAgree()
                } else {
                    this.$toast.fail('请登录后在进行订单支付!')
                    this.$router.push('/ticketing/loginIndex')
                }
            } else {
                this.$toast.fail('请阅读票品购买协议后进行支付!')
            }

            // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe07d768775a370d4&redirect_uri=${encodeURIComponent(window.location.href)}#wechat_redirect`
        },
        sureAgree() {
            this.$axios.post('/front/ticketAgreement', {
            }).then((res) => {
                this.createOrder()
            });
        },
        wxPay() {
            let payObj = {}
            if (this.openId) {
                payObj = {
                    Platform: 'h5',
                    OrderId: Number(this.orderId),
                    code: this.code,
                    openId: this.openId
                }
            } else {
                payObj = {
                    Platform: 'h5',
                    OrderId: Number(this.orderId),
                    code: this.code,
                }
            }
            this.$axios.post('/front/pay/doPay', payObj).then((response) => {
                const code = response.code
                const result = response.result
                if (code == 2) {
                    var currentUrl = window.location.href;
                    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe07d768775a370d4&redirect_uri=${encodeURIComponent(currentUrl)}&response_type=code&scope=snsapi_base&state=100#wechat_redirect`
                } else if (code != 0) {
                    alert('支付失败');
                } else {
                    this.callPaymentAPI(result)
                        .then(res => {
                            console.log(res, '支付完成');
                            // TODO: 支付成功处理
                        })
                        .catch(err => {
                            console.log('支付失败', err);
                            // TODO: 支付失败处理
                        });
                }
            });
        },
        showAgreement() {
            console.log(23123);
            // this.$dialog
            //   .confirm({
            //     title: `提示`,
            //     message: this.ticketAgreement,
            //   })
            //   .then(async () => {
            //   })
            //   .catch(() => {});
        },
        getAgree() {
            this.$axios.get('/front/ticketAgreement', {
            }).then((res) => {
                if (res.result == 1) {
                    this.isRead = true
                } else {
                    this.isRead = false
                }
            });
        },
        getCodes() {
            this.$axios.get(`/front/pay/getCode?code=${this.code}`, {
            }).then((res) => {
                if (res.result) {
                    this.openId = res.result
                }
            });
        }
    },
    created() {
        console.log(44,this.$store.state.collect.selectTicketInfo.info)
        if (this.$route.query.code) {
            localStorage.setItem('userCode', this.$route.query.code)
        }
        // if (!this.selectTicketInfo.info) {
        //     this.$router.push('/home')
        // }
        if (localStorage.getItem('userCode') != 'undefined') {
            this.code = localStorage.getItem('userCode')
        }
    },
    mounted() {
        this.onBridgeReady = this.onBridgeReady.bind(this);
        this.getAgree()
        if (this.$route.query.code) {
            this.code = this.$route.query.code;
            this.getCodes()
        }
    }
}
</script>
  
<style lang="less" scoped>
.pay {
    padding: .25rem .25rem 25vh;
    font-size: .3rem;
    background: #1a1b30;
}

.surePay {
    position: fixed;
    bottom: 0;
    left: 0;
    background: #1c1e37;
    height: 17vh;
    color: #fff;
    width: 100%;
    padding: .3rem .3rem 0;

    .sureTop {
        width: 100%;
        display: flex;
        justify-content: center;
        color: #5f5f77;
        margin-bottom: .4rem;

        .sureIcon {
            color: #fff;
            border: .02rem solid #444475;
            background: #333561;
            margin-right: .1rem;
            border-radius: .1rem;
            width: .4rem;
            height: .4rem;
            font-size: .24rem;
            line-height: .4rem;
            text-align: center;
        }
    }

    .sureBtm {
        display: flex;
        justify-content: space-between;
    }
}

.allMoney {
    width: 100%;
    color: #fff;

    .monTop {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: .3rem;
    }

    .monBtm {
        font-size: .25rem;
        color: #e8ebf1;
    }
}

.orderList {
    width: 100%;
    box-sizing: border-box;

    .orderItem {
        display: flex;
        justify-content: space-between;
        height: 2.6rem;
        font-size: .3rem;
        border-bottom: 1px solid #313247;
        padding-bottom: .3rem;
        margin-bottom: .2rem;

        .orderLef {
            width: 25%;
        }

        .orderRig {
            width: 75%;
            display: flex;
            flex-direction: column;
            justify-content: space-between;

            .tit {
                line-height: .5rem;
                font-size: .32rem;
            }

            .tickets {
                font-size: .24rem;
                width: 1.05rem;
                padding: .03rem 0;
                line-height: .4rem;
                border-radius: .14rem;
                text-align: center;
                color: #b5d9eb;
                background: #3f83f0;
            }

            .oRbottom {
                color: #6b6d84;
                font-size: .25rem;
                display: flex;
                justify-content: space-between;

                .oRLeft {
                    width: 70%;
                    display: flex;
                    justify-content: space-between;
                }
            }
        }
    }
}



.orderList {
    color: #fff;
}

.dorderItem {
    width: 100%;
    margin-bottom: .3rem;

    .title {
        font-size: .36rem;
        margin-bottom: .12rem;
    }

    .engTit {
        font-size: .23rem;
        margin-bottom: .14rem;
    }
}
</style>
  